package com.net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import com.constant.Constant;

public class AsyncRequest 
{
	/*Get请求只适用于发送大小在1024个字节以内的数据，如果需要发送的数据过大需要用Post方式
	 * Get方式，只需要在指定地址时，将要传递的参数通过"?参数名=参数值&参数名=参数值"进行传递即可
	 * 
	 * */
	
	public static final String HTTP_POST = "POST";
	public static final String HTTP_GET = "GET";

	
	/*Parameters：参数
	
	//RequestParameter网络请求中的参数,有该类中如下两个变量
		
	//private Bundle mParameters = new Bundle();
	//存放参数
		private ArrayList<String> mKeys = new ArrayList<String>();
		//存放关键字	*/
		
		
	//该函数的作用是：将请求的参数转换为一串字符串
		
	public static String encodeGetParameters(RequestParameter parameters)
	{
		if (parameters == null)
		{
			return "";
		}

		StringBuilder sb = new StringBuilder();//代表Http协议参数集合
		boolean first = true;
		for (int loc = 0; loc < parameters.size(); loc++)//parameters.size()是指关键字数组的大小
		{
			if (first)
				first = false;
			else
				sb.append("&");//第一个关键字和参数值前不加"&"符号，其他都要加
			
			sb.append(URLEncoder.encode(parameters.getKey(loc)) + "="
					+ URLEncoder.encode(parameters.getValue(loc)));
			//URLEncoder.encode把该字符串变为国际编码，这样中文才不会为乱码
			//URLEncoder.encode(String s)与下面的URLEncoder.encode(String s, "UTF-8")
			//是一样的效果
			//出来的格式为：关键字=参数&关键字=参数
		}
		return sb.toString();
	}
	
	
	public static String encodePostParameters(RequestParameter httpParams)
	{
		if (null == httpParams || httpParams.size() == 0)
		{
			return "";
		}
		StringBuilder buf = new StringBuilder();
		int j = 0;
		for (int loc = 0; loc < httpParams.size(); loc++)
		{
			String key = httpParams.getKey(loc);
			if (j != 0)
			{
				buf.append("&");
			}
			try
			{
				buf.append(URLEncoder.encode(key, "UTF-8"))
						.append("=")
						.append(URLEncoder.encode(httpParams.getValue(key),
								"UTF-8"));
			}
			catch (java.io.UnsupportedEncodingException neverHappen)
			{
			}
			j++;
		}
		return buf.toString();

	}
	
	/**
	 * 打开一个url，同时返回请求数据
	 */
	public static String openUrl(String url, String method,
			RequestParameter parameter) throws Exception
	{
		BasicHttpParams httpParameters = new BasicHttpParams();//初始化一个连接参数类
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				Constant.SET_CONNECTION_TIMEOUT);//设置连接超时时间，单位：毫秒
		HttpConnectionParams.setSoTimeout(httpParameters,
				Constant.SET_READ_TIMEOUT);//设置默认的套接字超时时间，单位：毫秒
		HttpClient client = new DefaultHttpClient(httpParameters);

		String rlt = null;
		
		try
		{
			/*所有的Http请求类，如HttpGet、HttpPost类都实现了HttpUriRequest接口
			*/
			HttpUriRequest request = null;
			ByteArrayOutputStream boStream = null;

			

			if (method.equals("GET"))
			{
				url = url + "?" + encodeGetParameters(parameter);
				HttpGet get = new HttpGet(url);

				request = get;
			}
			else if (method.equals("POST"))
			{
				HttpPost post = new HttpPost(url);
				byte[] data = null;
				boStream = new ByteArrayOutputStream(1024 * 50);

				post.setHeader("Content-Type",
						"application/x-www-form-urlencoded");
				String postParam = encodePostParameters(parameter);
				data = postParam.getBytes("UTF-8");
				///boStream.write(data);

				///data = boStream.toByteArray();
				boStream.close();
				//将参数转化为数组，然后用setEntity来设置请求参数
				ByteArrayEntity formEntity = new ByteArrayEntity(data);
				post.setEntity(formEntity);
				request = post;
			}
			
			request.setHeader("User-Agent", System.getProperties()
					.getProperty("http.agent"));
			HttpResponse response = client.execute(request);
			///StatusLine status = response.getStatusLine();
			///int statusCode = status.getStatusCode();
			if (response.getStatusLine().getStatusCode() == 200)
			{
				rlt = read(response);
				//把请求返回的数据读入rlt中
				
			}
			else
			{
				throw new Exception("数据请求返回结果错误！");
			}

		}
		catch (Exception ex)
		{
			throw new Exception(ex);
		}

		return rlt;
	}

	//通过HttpResponse返回字符串
	private static String read(HttpResponse response) throws Exception
	{
		HttpEntity entity = response.getEntity();
		InputStream inputStream;
		try
		{
			inputStream = entity.getContent();//取出服务器返回的数据流
			ByteArrayOutputStream content = new ByteArrayOutputStream();

			Header header = response.getFirstHeader("Content-Encoding");//Header为报头
			if (header != null
					&& header.getValue().toLowerCase().indexOf("gzip") > -1)
			{
				inputStream = new GZIPInputStream(inputStream);
			}

			// Read response into a buffered stream
			int readBytes = 0;
			byte[] sBuffer = new byte[512];
			while ((readBytes = inputStream.read(sBuffer)) != -1)//没有读到输入流的尾部
			{
				content.write(sBuffer, 0, readBytes);
			}
			if(content.size() == 0)
				return null;
			else 
				return new String(content.toByteArray());
		}
		catch (IllegalStateException e)
		{
			throw new Exception(e);
		}
		catch (IOException e)
		{
			throw new Exception(e);
		}
	} // read
}
